package net.dgg.zz.production.all.service;

import net.dgg.iboss.base.util.DesUtil;
import net.dgg.tmd.foundation.platform.common.util.TranslateUtil;
import net.dgg.tmd.foundation.platform.datapermission.entity.DataAuthDTO;
import net.dgg.tmd.foundation.platform.datapermission.service.DataPermissionAssocService;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.zz.common.constant.ScProductConstant;
import net.dgg.zz.common.service.CommonMangerExtService;
import net.dgg.zz.common.service.CommonService;
import net.dgg.zz.common.systemRecord.entity.SystemRecord;
import net.dgg.zz.common.systemRecord.service.SystemRecordService;
import net.dgg.zz.common.utils.StringUtils;
import net.dgg.zz.production.chargeback.dao.ZzProductOrderDao;
import net.dgg.zz.production.entity.ProductOrder;
import net.dgg.zz.production.inProcess.dao.ProductOrderDao;
import net.dgg.zz.production.inProcess.service.ZzInProcessService;
import net.dgg.zz.production.vo.OrderCountVo;
import net.dgg.zz.production.vo.OrgOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.sql.ParameterMetaData;
import java.util.*;

@Service
public class AllOrderService {

	@Autowired
	private ProductOrderDao productOrderDao;
	@Autowired
	private SessionManager sessionmanager;
	/**
	 * 注册接口
	 */
	@Autowired
	private CommonMangerExtService commonMangerExtService;
	
	@Autowired
	private DesUtil desUtil;
	@Autowired
	private CommonService commonService;
	@Autowired
	private TranslateUtil translateUtil;
	@Autowired
	private DataPermissionAssocService dataPermissionAssocService;
	@Autowired
	private SessionManager sessionManager;

	@Autowired
	private ZzProductOrderDao zzProductOrderDao;
	@Autowired
	private ZzInProcessService zzInProcessService;
	@Autowired
	private SystemRecordService systemRecordService;
	/**
	 * 查询多有已分配列表
	 * @param param
	 * @return
	 */
	public List<Map> allocatedScOrderWithPage(Map param){
		param.put("SC_TO_RECEIVE_XDDJS", ScProductConstant.SC_TO_RECEIVE_XDDJS);//新建待分配
		param.put("SC_ORDER_BACK_TO_ALLOT", ScProductConstant.SC_ORDER_BACK_TO_ALLOT);//退回待分配
		if(null!=param.get("customerPhone")){
			param.put("customerPhone",desUtil.encrypt(param.get("customerPhone").toString()));
		}
        if (null == param.get("orderColumn")) {
            param.put("orderDir", "desc");
            param.put("orderColumn", "allot_date");
        }
		UserEntity userEntity = sessionmanager.getCurrentUser();
	/*	Map map=commonMangerExtService.findBusDeptById(userEntity.getOrgId());
		if(null!=map)
			param.put("deptId",map.get("id"));
		else
			param.put("deptId",0);*/
		return productOrderDao.allocatedScOrderWithPage(param);
	}
	
	
	
	/**
	 * 查询我的所有生产订单列表
	 * @param param
	 * @return
	 */
	public List<Map> myScOrderWithPage(Map param){
		UserEntity userEntity = sessionmanager.getCurrentUser();
		param.put("userId",userEntity.getId());
		if(null!=param.get("customerPhone")){
			param.put("customerPhone",desUtil.encrypt(param.get("customerPhone").toString()));
		}
		if (null == param.get("orderColumn")) {
			param.put("orderDir", "desc");//排序方向
			param.put("orderColumn", "t.create_time");//排序的列
		}
		param.put("TIME_OUT_STATUS", ScProductConstant.TIME_OUT);
		return productOrderDao.myScOrderWithPage(param);
	}
	
	
	
	/**
	 * 查询部门所有生产订单列表
	 * @param param
	 * @return
	 */ 
	public List<Map> deptScOrderWithPage(Map param){
		param.put("SC_TO_RECEIVE_XDDJS", ScProductConstant.SC_TO_RECEIVE_XDDJS);//新建待分配
		param.put("SC_ORDER_BACK_TO_ALLOT", ScProductConstant.SC_ORDER_BACK_TO_ALLOT);//退回待分配
		param.put("SC_TO_RECEIVE_FPDJS", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收
		UserEntity userentity = sessionmanager.getCurrentUser();
		List<Long> id_item =commonMangerExtService.getChildOrganizationList(userentity.getOrgId());
		param.put("idList", id_item);
		if(null!=param.get("customerPhone")){
			param.put("customerPhone",desUtil.encrypt(param.get("customerPhone").toString()));
		}
		if (null == param.get("orderColumn")) {
			param.put("orderDir", "desc");//排序方向
			param.put("orderColumn", "t.create_time");//排序的列
		}
		param.put("deptId", userentity.getOrgId());
		param.put("TIME_OUT_STATUS", ScProductConstant.TIME_OUT);
		return productOrderDao.deptScOrderWithPage(param);
	}

	/**
	 * <p>@Description 部门生产订单导出</p>
	 * <p>@author zhangwen</p>
	 * <p>@Time 2018/8/31 0031 16:21 创建时间</p>
	 * <p>@return</p>
	 */
	public List<OrgOrderVo> findExportProductOrder(Map params) {
		params.put("SC_TO_RECEIVE_XDDJS", ScProductConstant.SC_TO_RECEIVE_XDDJS);//新建待分配
		params.put("SC_ORDER_BACK_TO_ALLOT", ScProductConstant.SC_ORDER_BACK_TO_ALLOT);//退回待分配
		params.put("SC_TO_RECEIVE_FPDJS", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收
		UserEntity userentity = sessionmanager.getCurrentUser();
		List<Long> id_item =commonMangerExtService.getChildOrganizationList(userentity.getOrgId());
		params.put("idList", id_item);
		if (null == params.get("orderColumn")) {
			params.put("orderDir", "desc");//排序方向
			params.put("orderColumn", "z.order_time_status,z.node_time_status,z.receive_time_status,z.distribution_time_out_status,t.update_time");//排序的列
		}
		params.put("deptId", userentity.getOrgId());
		params.put("TIME_OUT_STATUS", ScProductConstant.TIME_OUT);
		List<Map> srList = productOrderDao.deptScOrderWithPage(params);

		String[] transColum = {"originCode","status"};
		srList = translateUtil.translateList(transColum, srList);
		List<OrgOrderVo> voList = new LinkedList<>();
		for (Map map : srList) {
			OrgOrderVo vo = new OrgOrderVo();
			vo.setSignOrgName(String.valueOf(map.get("signOrgName") == null ? "" : map.get("signOrgName")));
			vo.setOrderNo(String.valueOf(map.get("orderNo") == null ? "" : map.get("orderNo")));
			vo.setScProductOrderNo(String.valueOf(map.get("scProductOrderNo") == null ? "" : map.get("scProductOrderNo")));
			vo.setCustomerName(String.valueOf(map.get("customerName") == null ? "" : map.get("customerName")));
			vo.setBusinessProductName(String.valueOf(map.get("businessProductName") == null ? "" : map.get("businessProductName")));
			vo.setProductName(String.valueOf(map.get("productName") == null ? "" : map.get("productName")));
			vo.setSignTime(String.valueOf(map.get("orderTime") == null ? "" : map.get("orderTime")));//签单时间
			vo.setSignUserName(String.valueOf(map.get("signUserName") == null ? "" : map.get("signUserName")));
			vo.setSignUserOrgName(String.valueOf(map.get("signUserOrgName") == null ? "" : map.get("signUserOrgName")));
			vo.setFlowUserName(String.valueOf(map.get("flowUserName") == null ? "" : map.get("flowUserName")));
			vo.setFlowUserOrgName(String.valueOf(map.get("flowUserOrgName") == null ? "" : map.get("flowUserOrgName")));
			vo.setOrderMoney(String.valueOf(map.get("money") == null ? "" : map.get("money")));//合同金额
			vo.setAssistUser(String.valueOf(map.get("assistUserName") == null ? "" : map.get("assistUserName")));//协单人员
			vo.setCompanyName(String.valueOf(map.get("companyName") == null ? "" : map.get("companyName")));//企业名称
			vo.setStatus(String.valueOf(map.get("status") == null ? "" : map.get("status")));//订单状态
			vo.setLatestEndNodeName(String.valueOf(map.get("latestEndNodeName") == null ? "" : map.get("latestEndNodeName")));//完成节点
			//最新备注时间
			vo.setLastRemarkTime(String.valueOf(map.get("lastRemarkTime") == null ? "" : map.get("lastRemarkTime")));
			vo.setLastRemark(String.valueOf(map.get("lastRemark") == null ? "" : map.get("lastRemark")));
			vo.setContractNo(String.valueOf(map.get("contractNo") == null ? "" : map.get("contractNo")));//合同编号
			voList.add(vo);
		}
		return voList;
	}
	
	
	
	/**
	 * 查询所有生产订单列表
	 * @param param
	 * @return
	 */
	public List<Map> allScOrderWithPage(Map param){
		param.put("SC_TO_RECEIVE_XDDJS", ScProductConstant.SC_TO_RECEIVE_XDDJS);//新建待分配
		param.put("SC_ORDER_BACK_TO_ALLOT", ScProductConstant.SC_ORDER_BACK_TO_ALLOT);//退回待分配
		param.put("SC_TO_RECEIVE_FPDJS", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收
		if(null!=param.get("customerPhone")){
			param.put("customerPhone",desUtil.encrypt(param.get("customerPhone").toString()));
		}
        if (null == param.get("orderColumn")) {
            param.put("orderDir", "desc");
            param.put("orderColumn", "t.create_time");
        }
		param.put("TIME_OUT_STATUS", ScProductConstant.TIME_OUT);
		return productOrderDao.allScOrderWithPage(param);
	}

	/**
	 * 修改流程人员
	 * @param ids
	 * @param flowUserId
	 * @return
	 */
	@Transactional
	public void updateFlowUser(List<Long> ids, Long flowUserId){
		UserEntity user = sessionManager.getCurrentUser();
		ids.forEach(id -> {
			ProductOrder scProductOrder = zzInProcessService.getScProductOrderById(id);
			Map flowUser = commonMangerExtService.searchUserById(flowUserId);
			Map org = commonMangerExtService.findOrg(Long.parseLong(flowUser.get("orgId").toString()));
			scProductOrder.setFlowUserId(Long.parseLong(flowUser.get("id").toString()));
			String flowUserName = scProductOrder.getFlowUserName();
			scProductOrder.setFlowUserName(flowUser.get("realName").toString().concat(flowUser.get("loginName").toString()));
			if (null != org) {
				scProductOrder.setFlowUserOrgId(Long.parseLong(org.get("id").toString()));
				scProductOrder.setFlowUserOrgName(org.get("name").toString());
			}
			//操作记录
			SystemRecord systemRecord = new SystemRecord();
			systemRecord.setWorkNo(scProductOrder.getScProductOrderNo());
			systemRecord.setWorkId(scProductOrder.getId());
			systemRecord.setWorkTableName("zzsc_product_order");
			systemRecord.setSource("2");//来源生产
			systemRecord.setOperateType("67");//操作类型 : 修改流程人员
			systemRecord.setRemarks("修改流程人员：原流程人员为【"+flowUserName+"】，调整后流程人员为【"+scProductOrder.getFlowUserName()+"】,修改人为【"+user.getRealName()+user.getLoginName()+"】");
			systemRecordService.save(systemRecord);
			zzProductOrderDao.update(scProductOrder);
		});
	}

	/**
	 * <p>@Description 团队待分配(超期)数据</p>
	 * <p>@author mqy</p>
	 * <p>@Time 2018/9/28 0028 11:05 创建时间</p>
	 * <p>@return</p>
	 */
	public List<Map> teamAllotDeptProductOrderData(Map param){
		UserEntity userentity = sessionmanager.getCurrentUser();
		if(null!=param.get("customerPhone")){
			param.put("customerPhone",desUtil.encrypt(param.get("customerPhone").toString()));
		}
		//查本事业部的
		Long userSybId = commonService.findUserSyb(userentity);//查事业部ID
		param.put("productOrgId",userSybId);
		if (StringUtils.isNotEmpty(param.get("isTimeOUt")) && Integer.valueOf(param.get("isTimeOUt").toString()) == 1){
			param.put("TEAM_TIME_OUT_STATUS", ScProductConstant.TIME_OUT);//团队超期
		}
		param.put("TeamAllotStatus", "yes");//表示团队待接收
		param.put("SC_TO_RECEIVE_XDDJS", ScProductConstant.SC_TO_RECEIVE_XDDJS);//新建待分配
		param.put("SC_ORDER_BACK_TO_ALLOT", ScProductConstant.SC_ORDER_BACK_TO_ALLOT);//退回待分配
		return productOrderDao.deptScOrderWithPage(param);
	}


	/**
	* <p>@Description 团队待接收数据</p>
	* <p>@author mqy</p>
	* <p>@Time 2018/9/28 0028 11:05 创建时间</p>
	* <p>@return</p>
	*/
	public List<Map> teamReceiveDeptProductOrderData(Map param){
		UserEntity userentity = sessionmanager.getCurrentUser();
		List<Long> id_item =commonMangerExtService.getChildOrganizationList(userentity.getOrgId());
		param.put("idListByReceive", id_item);
		if(null!=param.get("customerPhone")){
			param.put("customerPhone",desUtil.encrypt(param.get("customerPhone").toString()));
		}
         if (StringUtils.isNotEmpty(param.get("isTimeOUt")) && Integer.valueOf(param.get("isTimeOUt").toString()) == 1){
             param.put("TEAM_RECEIVE_TIME_OUT_STATUS", ScProductConstant.TIME_OUT);//团队超期
         }
		param.put("deptId", userentity.getOrgId());
		param.put("TIME_OUT_STATUS", ScProductConstant.TIME_OUT);
		param.put("TeamReceiveStatus", "yes");//表示团队待接收
		param.put("SC_TO_RECEIVE_FPDJS", ScProductConstant.SC_TO_RECEIVE_FPDJS);//分配待接收
		param.put("SC_TO_RECEIVE_ZDDJS", ScProductConstant.SC_TO_RECEIVE_ZDDJS);//转单待接收
		param.put("SC_TO_RECEIVE_YJDJS", ScProductConstant.SC_TO_RECEIVE_YJDJS);//移交待接收
		param.put("SC_TO_RECEIVE_TDDJS", ScProductConstant.SC_TO_RECEIVE_TDDJS);//退回待接收
		return productOrderDao.deptScOrderWithPage(param);
	}

	/**
	* <p>@Description 团队办理超期数据</p>
	* <p>@author mqy</p>
	* <p>@Time 2018/10/22 0022 14:40 创建时间</p>
	* <p>@return</p>
	*/
     public List<Map> teamInprocessTimeOutData(Map param) {
         UserEntity userentity = sessionmanager.getCurrentUser();
         if (null != param.get("customerPhone")) {
             param.put("customerPhone", desUtil.encrypt(param.get("customerPhone").toString()));
         }
         ////获取本部门及所有下属部门ID
         List<Long> childOrganizationList = commonMangerExtService.getChildOrganizationList(userentity.getOrgId());
         param.put("flowerUserOrganizationList", childOrganizationList);
         param.put("TeamOrderTimeOutStatus", "OVERDUE_STATE2");//表示办理超期
         param.put("TIME_OUT_STATUS", ScProductConstant.TIME_OUT);
         //不包含（已完结、已结项、已退单、待分配）
         param.put("notStatusList", new String[]{ScProductConstant.SC_ORDER_OVER
                 , ScProductConstant.SC_ORDER_OVER_OVERDUE, ScProductConstant.SC_ORDER_OVER_FORCE
                 , ScProductConstant.SC_ORDER_JUNCTIONS, ScProductConstant.SC_ORDER_FINISHED_CHARGEBACK
                 , ScProductConstant.SC_TO_RECEIVE_XDDJS, ScProductConstant.SC_ORDER_BACK_TO_ALLOT});
         return productOrderDao.deptScOrderWithPage(param);
     }

     /**
     * <p>@Description 方法的功能描述</p>
     * <p>@author mqy</p>
     * <p>@Time 2018/11/7 0007 10:30 创建时间</p>
     * <p>@return</p>
     */
     public Map scOrderCountData(Map param){
		UserEntity userentity = sessionmanager.getCurrentUser();
		Map resultMap = new HashMap();
		if ("1".equals(param.get("isAll"))){
			//有查看全部的权限并且没有传事业部条件进来才查总的
			if (StringUtils.isEmpty(param.get("signOrgId"))){
				Map map = productOrderDao.selectScOrderCountTotal(param);
				resultMap.put("orderTotal",map);
			}
          }else {
			//没有看全部的权限就查自己所在事业部的
			Long userSybId = commonService.findUserSyb(userentity);//查事业部ID
			param.put("signOrgId",userSybId);
		}
		List<Map> maps = productOrderDao.selectScOrderCount(param);
          resultMap.put("orderCount",maps);
		return  resultMap;
	}


	public List<OrderCountVo> exportOrderCountData(Map param){
		List<Map> maps = productOrderDao.selectScOrderCount(param);
		List<OrderCountVo> orderCountVoList = new ArrayList<>();
		if (maps != null && !maps.isEmpty()){
			for (Map map : maps) {
				OrderCountVo orderCountVo = new OrderCountVo();
				orderCountVo.setProductOrgName(map.get("productOrgName") == null ? "" :map.get("productOrgName").toString());
				orderCountVo.setWaitAllotCount(map.get("waitAllotCount") == null ? "0" :map.get("waitAllotCount").toString());
				orderCountVo.setWaitReceiveCount(map.get("waitReceiveCount") == null ? "0" :map.get("waitReceiveCount").toString());
				orderCountVo.setInprocessCount(map.get("inprocessCount") == null ? "0" :map.get("inprocessCount").toString());
				orderCountVo.setSuspendCount(map.get("suspendCount") == null ? "0" :map.get("suspendCount").toString());
				orderCountVo.setChargeBackingCount(map.get("chargeBackingCount") == null ? "0" :map.get("chargeBackingCount").toString());
				orderCountVo.setChargeBackBhCount(map.get("chargeBackBhCount") == null ? "0" :map.get("chargeBackBhCount").toString());
				orderCountVo.setChargeBackedCount(map.get("chargeBackedCount") == null ? "0" :map.get("chargeBackedCount").toString());
				orderCountVo.setOrderOverCount(map.get("orderOverCount") == null ? "0" :map.get("orderOverCount").toString());
				orderCountVo.setOrderJuncttonCount(map.get("orderJuncttonCount") == null ? "0" :map.get("orderJuncttonCount").toString());
				orderCountVo.setOrderJuncttonCount(map.get("orderJuncttonCount") == null ? "0" :map.get("orderJuncttonCount").toString());
				orderCountVo.setOrderStopCount(map.get("orderStopCount") == null ? "0" :map.get("orderStopCount").toString());
				orderCountVo.setTotal(map.get("total") == null ? "0" :map.get("total").toString());
				orderCountVoList.add(orderCountVo);
			}
		}
		//传了事业部进来就不用查总的了
		if ("1".equals(param.get("isAll")) || StringUtils.isEmpty(param.get("signOrgId"))){
			Map map = productOrderDao.selectScOrderCountTotal(param);
			OrderCountVo orderCountVo = new OrderCountVo();
			orderCountVo.setProductOrgName("总计");
			orderCountVo.setWaitAllotCount(map.get("waitAllotTotal") == null ? "0" :map.get("waitAllotTotal").toString());
			orderCountVo.setWaitReceiveCount(map.get("waitReceiveTotal") == null ? "0" :map.get("waitReceiveTotal").toString());
			orderCountVo.setInprocessCount(map.get("inprocessTotal") == null ? "0" :map.get("inprocessTotal").toString());
			orderCountVo.setSuspendCount(map.get("suspendTotal") == null ? "0" :map.get("suspendTotal").toString());
			orderCountVo.setChargeBackingCount(map.get("chargeBackingTotal") == null ? "0" :map.get("chargeBackingTotal").toString());
			orderCountVo.setChargeBackBhCount(map.get("chargeBackBhTotal") == null ? "0" :map.get("chargeBackBhTotal").toString());
			orderCountVo.setChargeBackedCount(map.get("chargeBackedTotal") == null ? "0" :map.get("chargeBackedTotal").toString());
			orderCountVo.setOrderOverCount(map.get("orderOverTotal") == null ? "0" :map.get("orderOverTotal").toString());
			orderCountVo.setOrderJuncttonCount(map.get("orderJuncttonTotal") == null ? "0" :map.get("orderJuncttonTotal").toString());
			orderCountVo.setOrderStopCount(map.get("orderStopCount") == null ? "0" :map.get("orderStopCount").toString());
			orderCountVo.setTotal(map.get("allTotal") == null ? "0" :map.get("allTotal").toString());
			orderCountVoList.add(orderCountVo);
		}
		return  orderCountVoList;
	}

	public List<Map> stopScOrderWithPage(Map param) {
		beforeQuery(param);
		if (null == param.get("orderColumn")) {
			param.put("orderDir", "desc");
			param.put("orderColumn", "t.update_time");
		}
		//return productOrderDao.allScOrderWithPage(param);
		return productOrderDao.stopScOrderWithPage(param);
	}

	/**
	 * @param paras
	 */
	private void beforeQuery(Map paras) {
		String code = paras.get("dataAuthority").toString();
		//设置当前登录人
		UserEntity user = sessionManager.getCurrentUser();
		Assert.notNull(user, "检测到当前未登录。");
		DataAuthDTO dataAuthDTO = dataPermissionAssocService.selectAuthToConfigureRturnOrgIds(code);
		paras.put("userId", user.getId());
		paras.put("dataAuthDTO", dataAuthDTO);
		paras.put("userAlias", "t");
		paras.put("userColumn", "flow_user_id");
		paras.put("deptAlias", "t");
		paras.put("deptColumn", "flow_user_org_id");

		//查询条件号码加密
		if (!net.dgg.iboss.base.util.StringUtils.isEmptyObj(paras.get("customerPhone"))) {
			paras.put("customerPhone", desUtil.encrypt(paras.get("customerPhone").toString()));
		}
	}

	public List<Map> customerScOrderWithPage(Map params) {
		if(null!=params.get("customerPhone")){
			params.put("customerPhone",desUtil.encrypt(params.get("customerPhone").toString()));
		}
		UserEntity userentity = sessionmanager.getCurrentUser();
		Long userSybId=0l;
		//查本事业部的
		try {
			 userSybId = commonService.findUserSyb(userentity);//查事业部ID
		}catch (Exception e){
			userSybId = 0l;
		}
		if(0l !=userSybId) {
			params.put("productOrgId", userSybId);
		}
		return productOrderDao.customerScOrderWithPage(params);
	}

	public List<Map> findCustomerInfo(Map map) {
		UserEntity userentity = sessionmanager.getCurrentUser();
		Long userSybId=0l;
		//查本事业部的
		try {
			userSybId = commonService.findUserSyb(userentity);//查事业部ID
		}catch(Exception e){
			userSybId=0l;
		}
		if(0l != userSybId) {
			map.put("productOrgId", userSybId);
		}
		return productOrderDao.allScOrderWithPage(map);
	}

    public Map findOrderById(Long id) {
		Map map = new HashMap();
		map.put("id",id);
		return productOrderDao.queryProductMap(map);
    }
}
